import axios from "axios";
import router from "./router";

axios.defaults.timeout = 30000;
// axios.defaults.baseURL = "http://192.168.0.13:8001/v1"; //测试地址
axios.defaults.baseURL = baseUrl.bsIp + "/v1"; //线上测试地址   玉龙

axios.defaults.Token = null;
var ItemIp = null;
//http request 拦截器
console.log("获取axios");
// console.log(axios.defaults);
axios.interceptors.request.use(
  (config) => {
    config.data = JSON.stringify(config.data);
    config.headers = {
      "content-type": "application/json;charset=UTF-8",
      Token: localStorage.getItem("Token"),
      // Token: "C0FD61EDA8A94248B1033706BD090555",
      // Token: "ytsoftware2019",
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export function setToken(Token) {
  axios.defaults.Token = Token;
}

export function getToken() {
  return axios.defaults.Token;
}

//http response 拦截器
var dz = "";
var index = 0;
axios.interceptors.response.use(
  (response) => {
    if (response.data.errCode == 2) {
      // router.push({
      //     path: "/login",
      //     querry: {redirect: router.currentRoute.fullPath}//从哪个页面跳转
      // })
    }
    index = 0;
    return response;
  },
  (error) => {
    console.log("请求返回异常消息error");
    console.log(error.response);
    console.log(error.response.status);
    this.$notify.error({
      title: "错误码" + error.response.status,
      message: error.response.data.msg,
    });
    if (error.response.status === 401) {
      if (ItemIp != null) {
        axios.defaults.Token = null;
        window.location.href = ItemIp + "/#/ToLogin";
        // window.open(ItemIp+'/#/ToLogin');
        window.window.close();
      } else {
        axios.defaults.Token = null;
        router.replace({
          path: "/login",
        });
        if (index == 0) {
          alert("登录信息已过期，请重新登录");
          index = 1;
        }
      }
    }
    return Promise.reject(error);
  }
);

export function getBaseUrl() {
  return axios.defaults.baseURL;
}

export function getBaseIP() {
  return baseIP;
}

export function setBaseUrl(url) {
  dz = url;
  axios.defaults.baseURL = url;
}

export function setItemUrl(url) {
  ItemIp = url;
}

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
export function postG(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, { params: params }).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
/**
 * 封装DELETE请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function deleteF(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/****************************************WebShoket***************************************/

var socket = null;

// 调用
export function scanTemperature(File, Display, Data, getMsg) {
  var sendPrintMsg = {
    SevAddress: "http://114.115.149.212:13155",
    Token: axios.defaults.Token,
    Code: "Temperature",
    Input: {
      File: File,
      Display: Display, //0:预览，1：不预览
      Data: Data, //"附加动态参数,每个打印不同"
    },
  };
  var sendMsg = JSON.stringify(sendPrintMsg);
  scanIdCard(sendMsg, getMsg);
}

// 调用
export function scanOpen(File, Display, Data, getMsg, Code) {
  var sendPrintMsg = {
    SevAddress: "http://114.115.149.212:13155",
    Token: axios.defaults.Token,
    Code: Code,
    Input: {
      File: File,
      Display: Display, //0:预览，1：不预览
      Data: Data, //"附加动态参数,每个打印不同"
    },
  };
  var sendMsg = JSON.stringify(sendPrintMsg);
  scanIdCard(sendMsg, getMsg);
}

// 检查检验调用
export function scanOpenJC(Kind, StudyId, getMsg) {
  var sendPrintMsg = {
    SevAddress: "http://114.115.149.212:6676",
    Token: axios.defaults.Token,
    Code: "ImageViewer",
    Input: {
      Kind: Kind, //影像类型(PACS/US/ECG/)"
      StudyId: StudyId, //0:预览，1：不预览
      File: "",
      Display: "1",
    },
  };
  var sendMsg = JSON.stringify(sendPrintMsg);
  scanIdCard(sendMsg, getMsg);
}

// 调用
export function scanPrint(File, Display, Data, getMsg) {
  var sendPrintMsg = {
    SevAddress: "http://114.115.149.212:13155",
    Token: axios.defaults.Token,
    Code: "PrintFile",
    Input: {
      File: File,
      Display: Display, //0:预览，1：不预览
      Data: Data, //"附加动态参数,每个打印不同"
    },
  };
  var sendMsg = JSON.stringify(sendPrintMsg);
  scanIdCard(sendMsg, getMsg);
}

// 调用
export function scanIdCard(sendMsg, getMsg) {
  openReader(getMsg);
  setTimeout(function() {
    readIDCard(sendMsg, getMsg);
  }, 500);
}

//打开
export function openReader(getMsg) {
  var host = "ws://127.0.0.1:7181";
  if (socket == null) {
    socket = new WebSocket(host);
    console.log("开启socket服务");
  } else {
  }
  try {
    socket.onopen = function(msg) {};
    socket.onerror = function() {
      alert("请检查设备服务是否成功开启.");
      getMsg(null);
      closeSocket();
    };
    socket.onmessage = function(msg) {
      if (typeof msg.data == "string") {
        var msgM = msg.data + "";
        console.log("调取硬件返回数据");
        console.log(msgM);
        try {
          var msgObj = JSON.parse(msgM);
          if (msgObj.code == 0) {
            getMsg(msgM);
            closeSocket();
          }
        } catch (e) {
          console.log("解析异常");
          getMsg(null);
          closeSocket();
        }
      } else {
        alert("连接异常,请检查是否成功安装驱动.");
        getMsg(null);
        closeSocket();
      }
    };
  } catch (ex) {}
}

//发送
export function readIDCard(sendMsg, getMsg) {
  try {
    if (socket.readyState !== 1) {
      releaseDisabled(index);
      socket = null;
      return;
    }
    console.log("打印发送消息");
    console.log(sendMsg);
    socket.send(sendMsg);
  } catch (ex) {
    alert("连接异常,请检查驱动.");
    getMsg(null);
    closeSocket();
  }
}

//关闭
export function closeSocket() {
  try {
    if (socket != null) {
      console.log("关闭socket服务");
      socket.close();
      socket = null;
    }
  } catch (ex) {}
}
